//
//  OAuthViewController.swift
//  Weibo
//
//  Created by mac on 15/11/27.
//  Copyright © 2015年 zsl. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

 class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    override func loadView() {
        //将底部的根视图替换成webView
        view = webView
        webView.delegate = self
    }
    
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
     //mark:处理自动填充按钮
   @objc private func defaultAccount(){
    
    //本地代码和通讯
    
    let jsString = "document.getElementById('userId').value = '18399226929', document.getElementById('passwd').value = 'w123456' "
    webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //输出视图类型
            //controllers is discouraged <Weibo.HomeTableViewController: 0x7fde53de29b0>.
            //------- UIWebView
       // print("-------",view.classForCoder)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        //调加载页面方法
        loadOAuthPage()
    }
     //mark:加载授权页面
    private func loadOAuthPage(){
        //      请求用户授权Token   + 申请应用时分配的AppKey。+ 申请应用时分配的AppKey的值 + 授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。+回调的网页地址
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" +
            "2786496718" + "&redirect_uri=" + "http://www.baidu.com"
       // let urlString = "https://api.weibo.com/oauth2/access_token?" + "client_id=" +
           // client_id + "&redirect_uri=" + redirect_uri
       
        //判断url是否有值
        if let url = NSURL(string: urlString){
            let request = NSURLRequest(URL: url)
            //加载页面
            webView.loadRequest(request)
        }
        

    }
}
/**
*  使用extension为当前类直接扩展协议方法
*/
extension OAuthViewController:UIWebViewDelegate{
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭
        SVProgressHUD.dismiss()
        
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //监测网页正在请求哪一个url
    //Bool  协议方法 返回值为bool
    //如果返回true  持有协议的对象 就可以正常工作 否则就不行
    /**
    URL: https://api.weibo.com/oauth2/authorize?client_id=2786496718&redirect_uri=http://www.baidu.com  加载微博登陆页面的url
    
    URL: https://api.weibo.com/oauth2/authorize  微博的授权页面
    
    //授权成功之后加载百度页面的url
    URL: https://api.weibo.com/oauth2/authorize# }
     { URL: https://api.weibo.com/oauth2/authorize }
     { URL: http://www.baidu.com/?code=a15895ff5ae804d86790edd96fb81f4b }
    { URL: https://m.baidu.com/?code=a15895ff5ae804d86790edd96fb81f4b&from=844b&vit=fps }
    { URL: about:blank }
    
    //注册页面的url
    URL: http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=4urg5M&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2786496718%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.baidu.com%26from%3D%26with_cookie%3D
     http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=4urg5M&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2786496718%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.baidu.com%26from%3D%26with_cookie%3D
    
    code=42d1b4d8ec15aa0c3e83c925a137bd74 //授权页面的code
    code=f7b5ca850a6f96686b67cdc35e979691 //回调页面的code

    */
     func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
      // print("xx",request)
        let urlString = request.URL?.absoluteString ?? ""
        //屏蔽不希望加载的页面
        if urlString.hasPrefix( "https://api.weibo.com/"){
            return true
        }
        if !urlString.hasPrefix("http://www.baidu.com/"){
        
      return false
    }
        
        //程序如果走到这里  就只有包含回调的url才能运行到此
        //query 查询
        //获取授权码
        guard let quary = request.URL?.query  else{
            
            
            //获取不到参数列表
            return false
        }
        print(urlString)//http://www.baidu.com/?code=299a05d3dee277450f3e1ace9a1a3093
        print(quary)//code=299a05d3dee277450f3e1ace9a1a3093
       
        //获取到code码
        let codeStr = "code="
        let code = quary.substringFromIndex(codeStr.endIndex)
        print("1",code)//299a05d3dee277450f3e1ace9a1a3093
        
        //调用
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            if error != nil{
                
                SVProgressHUD.showErrorWithStatus("你的网络错误")
                return
            }
        }
        
        SVProgressHUD.showSuccessWithStatus("登陆成功")
        
        
        print("调用",code)
        
    return false
}
    
}

